package com.gjm.demo.controller;

import com.gjm.demo.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * 注解事务
 */
@RestController
@RequestMapping("/user2")
public class UserInfoController2 {

    @Autowired
    private UserInfoService userInfoService;

    @Transactional
    @RequestMapping("/registry")
    public String insertUserInfo(String username, String password) throws IOException {

        //用户注册
        Integer result = userInfoService.insertUserInfo(username, password);

//        //抛出异常，事务回滚
//        int a = 1 / 0;

//        //捕获异常，事务不回滚
//        try {
//            int a = 1 / 0;
//        } catch (Exception e) {
//            System.out.println("发生异常");
//        }

        //只有 Error 和 RuntimeException 才会回滚，其它的异常不会回滚
        if (true) {
            throw new IOException();
        }

        return "插入成功";
    }

    //自定义哪些异常需要回滚
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping("/registry2")
    public String insertUserInfo2(String username, String password) throws IOException {
        Integer result = userInfoService.insertUserInfo(username, password);

        if (true) {
            throw new IOException();
        }

        return "插入成功";

    }
}
